﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.SceneManagement;
using UnityEditor.UI;
using UnityEngine;

public class FightManger : MonoBehaviour
{
    public static FightManger Instance;

    private GameObject mapGob;
    private GameObject playerGob;
    private GameObject enemyGob;
    private List<CharactorCtrl> charactors = new List<CharactorCtrl>();
    private CharactorCtrl self;
    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        playerGob = LoadCharacter("Self/20001", 20001,  true);
        playerGob.transform.localPosition = new Vector3(0, 5, 0);
        playerGob.transform.LookAt(new Vector3(1, 0, 0));
        self = playerGob.GetComponent<CharactorCtrl>();
        
        
        enemyGob = LoadCharacter("Enemy/20001", 20002, false);
        enemyGob.transform.LookAt(new Vector3(-1, 0, 0));
        enemyGob.transform.localPosition = new Vector3(0, -5, 0);
        
        EventMgr.Instance.AddListener((int)EventTypes.UI, this.OnUIEventProc);
        
        SkillManager.Instance.Init();
        BuffManager.Instance.Init();
        
    }

    public void OnUIEventProc(int eventType, object udata, object param = null)
    {
        switch ((int)udata)
        {
            case (int) UIEvents.Skill:
                OnProcessSkill((int)param);
                break;
            case (int) UIEvents.Buff:
                OnProcessBuff((int)param);
                break;
        }
    }


    public GameObject LoadCharacter(string characterName, int id, bool isSelfCharactor)
    {
        string assetPath = $"Charactors/Prefabs/{characterName}";
        GameObject playerGob = AssetManager.Instance.LoadAndInstantiatePrefab(assetPath);
        playerGob.transform.SetParent(this.transform, false);
        playerGob.transform.localPosition = Vector3.zero;
        CharactorCtrl ctrl = playerGob.AddComponent<CharactorCtrl>();
        charactors.Add(ctrl);
        ctrl.Init(id, isSelfCharactor);
        return playerGob;
    }
    
    public void OnProcessBuff(int buffId/*, int uid*/) {
        this.self.StartBuff(buffId);
    }

    public void OnProcessSkill(int skillId/*, int uid*/)
    {
        this.self.StartSkill(skillId);
    }

    /// <summary>
    /// 获取攻击范围内的所有敌人
    /// </summary>
    /// <param name="sender">攻击方</param>
    /// <param name="resultAttackR">攻击范围</param>
    /// <returns></returns>
    public List<CharactorCtrl> FindTargetsInArea(CharactorCtrl sender, float resultAttackR)
    {
        List<CharactorCtrl> targets = new List<CharactorCtrl>();
        foreach (var charactor in charactors)
        {
            if (charactor.isSelf != sender.isSelf )
            {
                targets.Add(charactor);
            }
        }
        return targets;
    }
}
